package com.holdtime.wisdomdrone.module.service.impl;

import cn.iocoder.yudao.module.infra.framework.file.core.client.FileClient;
import cn.iocoder.yudao.module.infra.service.file.FileConfigService;
import cn.iocoder.yudao.module.infra.service.file.FileService;
import com.holdtime.wisdomdrone.module.model.config.UploadFileConfig;
import com.holdtime.wisdomdrone.module.service.UploadOssFileService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * author: qzj
 * Date: 2024/2/25 15:25
 * Description: 上传OSS文件实现类
 */
@Service
@Validated
@Slf4j
public class UploadOssFileServiceImpl implements UploadOssFileService {
    @Resource
    private FileService fileService;
    @Resource
    private FileConfigService fileConfigService;
    @Resource
    private UploadFileConfig config;
    @Override
    public boolean uploadOssFileByKey(String ossKey,String path) {
        FileClient client = fileConfigService.getMasterFileClient();
        try {
            byte[] fileBytes = fileService.getFileContent(client.getId(),ossKey);
            // 指定文件路径
            String rootPath = config.getFilePath();
            String filePath = rootPath + "/" + path + "/" + ossKey.split("/")[1];
            // 创建目录（如果不存在）
            Path directoryPath = Paths.get(rootPath + "/" + path);
            Files.createDirectories(directoryPath);
            try (FileOutputStream fos = new FileOutputStream(filePath)) {
                fos.write(fileBytes);
            } catch (IOException e) {
                log.error("写入文件失败:{}",e.getMessage());
                return false;
            }
        } catch (Exception e) {
            log.error("读取文件失败:{}",e.getMessage());
            return false;
        }
        return true;
    }
}
